<?php
use Pingpp\Pingpp;
/**
 * 充值控制类
 */
class RechargeAction extends Action{
	public function _initialize(){
	
		require ("apps/apis/Lib/Widget/Pingpp/init.php");
	}
	public function pay(){
		$input_data["uid"] = dt($_REQUEST["uid"]);
		$input_data["money"] = dt($_REQUEST["money"]);
		$input_data["credit"] = dt($_REQUEST["credit"]);
		$input_data["subject"] = dt($_REQUEST["subject"]);
		$input_data["body"] = dt($_REQUEST["body"]);
		$input_data["channel"] = dt($_REQUEST["channel"]);
// 		 $input_data = array(
// 		 		"uid" =>"23",
// 		 		"money"=>"1",
// 		 		"credit"=>23,
// 		 		"ctime"=>"秒杀商品1",
// 		 		"channel"=>"广州天河",
// 		 		"order_no"=>"13512754398",
// 		 		"subject"=>"2015",
// 		 		"body" => "test_body",
// 		 		"channel"=>"alipay_wap",
// 		 		
// 		 );
		
		if (empty($input_data['channel']) || empty($input_data['amount'])) {
			//die(json_encode("empty"));
		}
		$channel = strtolower($input_data['channel']);
		$amount = $input_data['money'];
		$orderNo = substr(md5(time()), 0, 12);
		$body = isset($input_data["body"])?$input_data["body"]:"nonobody";
		$subject = $input_data["subject"];
		//$extra 在使用某些渠道的时候，需要填入相应的参数，其它渠道则是 array() .具体见以下代码或者官网中的文档。其他渠道时可以传空值也可以不传。
		$extra = array();
		
		switch ($channel) {
	
			case 'alipay_wap':
				$extra = array(
				'success_url' => C("__PAYURL__").'paysuccess',
				'cancel_url' => C("__PAYURL__").'paycancel'
						);
						break;
			case 'upmp_wap':
				$extra = array(
				'result_url' => C("__PAYURL__").'Webhooks'
						);
						break;
			case 'bfb_wap':
				$extra = array(
				'result_url' => C("__PAYURL__").'Webhooks',
				'bfb_login' => true
				);
				break;
			case 'upacp_wap':
				$extra = array(
				'result_url' => C("__PAYURL__").'Webhooks'
						);
						break;
			case 'wx_pub':
				$extra = array(
				'open_id' => 'Openid'
						);
						break;
			case 'wx_pub_qr':
				$extra = array(
				'product_id' => 'Productid'
						);
						break;
		}
			
		
		\Pingpp\Pingpp::setApiKey(C("__SECRETKEY__"));
		
		try {
			$ch = \Pingpp\Charge::create(
					array(
							'subject'   => $subject,
							'body'      => $body,
							'amount'    => $amount,
							'order_no'  => $orderNo,
							'currency'  => 'cny',
							'extra'     => $extra,
							'channel'   => $channel,
							'client_ip' => $_SERVER['REMOTE_ADDR'],
							'app'       => array('id' => C('__APPID__'))
					)
			);
			header("Content-Type: text/json");
			echo $ch;
				
		} catch (\Pingpp\Error\Base $e) {
			header('Status: ' . $e->getHttpStatus());
			echo($e->getHttpBody());
		}
		//保存交易记录	
		$this->buildOrder($ch, $input_data);
	}
	
	public function Webhooks(){
	
		$event = json_decode(file_get_contents('php://input'),true);
		// 对异步通知做处理
		if (!isset($event['type'])) {
			header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
			exit("fail");
		}
		switch ($event['type']) {
			case "charge.succeeded":
				// 对支付异步通知的处理
				$this->paysucc($event);
				header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
				break;
			case "refund.succeeded":
				// 开发者在此处加入对退款异步通知的处理代码
				header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
				break;
			default:
				$this->paycancel($event);
				header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
				break;
		}
	
	}
	public function verify_signature($raw_data, $signature, $pub_key_path) {
		$pub_key_contents = file_get_contents ( $pub_key_path );
		return openssl_verify ( $raw_data, base64_decode ( $signature ), $pub_key_contents, OPENSSL_ALGO_SHA256 );
	}
	//建立订单
	public function buildOrder($ch,$input_data){
		$data = (array)json_decode($ch);
		//获取数据，新增数据
		$order = M("User_recharge");
		//用户商店商品id
		$order->uid = $input_data['uid'];
		$order->money = $input_data['money'];
		$order->credit = $input_data['credit'];
		$order->ctime = time();
		$order->pid = $data['id'];
		//支付信息
		$order->channel = $data['channel'];//支付类型
		//订单详情
		$order->subject = $data['subject'];//名称
		$order->body = $data['body'];//名称
		$order->order_no = $data['order_no'];
	
		//增加订单
		$order->add();
	}
	
	//支付成功
	public function paysuccess($input_data=null){
		//接收数据
		if($input_data == null){
			$input_data = json_decode(file_get_contents('php://input'), true);
		}
		//修改数据库
	
		if($input_data['type'] == 'charge.succeeded')
		{
			//支付成功
			$order = M("User_recharge");
			$order->startTrans();
			$order_no =  $input_data['data']["object"]['order_no'];
			$order->status = "pay";
			if($order->where("order_no = '$order_no'")->save()){
			//修改用户积分状态
				$data = $order->where("order_no = '$order_no'")->find();
				$uid = $data["uid"];
				$credit = $data["credit"];
				if(M("Credit_user")->setInc("score",$credit)){
					$order->commit();
				}
			}
			
			
				
		}
	}
	public function paysucc($event=null){
		$order = M("User_recharge");
		$order_no = $event['data']["object"]['order_no'];
		$order->status = "pay";
		echo $order->where("order_no = '$order_no'")->save();
	
	
	}
	//支付失败
	public function paycancel($input_data=null){
		//接收数据
	
		//修改数据库
		if($input_data == null){
			$input_data = json_decode(file_get_contents('php://input'), true);
		}
		if($input_data['type'] == 'charge.succeeded')
		{
			$order = M("User_recharge");
			$order->status = "cancel";
			$order_no =  $input_data['data']["object"]['id'];
			if($order->where("order_no = $order_no")->save()){
				
			}		
		}
	}
	
}